﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace SobFS.Web
{
    public partial class Test : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            BLL.SysUser user = new BLL.SysUser();
            user.GetModelByCache(1);

        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            const long blockSize = 102400;//100K 每次读取文件，只读取100Ｋ，这样可以缓解服务器的压力
            string fileName = "关键词助手完整安装包.zip";//客户端保存的文件名
            string filePath = Server.MapPath("downloads/KeywordAssistant.zip");//路径

            FileInfo fileInfo = new FileInfo(filePath);
            if (fileInfo.Exists)
            {
                byte[] buffer = new byte[blockSize];

                Response.Clear();
                FileStream iStream = File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(blockSize));//读取的大小
                    Response.OutputStream.Write(buffer, 0, lengthRead);
                    Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                Response.Close();
            }
        }

        string filepath = @"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\cert.cer";
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //生成密钥
            this.txtKey.Text = BuildEncryptKey();
            string key = this.txtKey.Text.Trim();

            //加密后的文件名
            string encryptCertFile = string.Format("encrypt-cert-{0}.cer", key);

            //3DES加密过程为：C=Ek3(Dk2(Ek1(P))) 
            using (StreamReader sr = new StreamReader(filepath, Encoding.UTF8))
            {
                string p = sr.ReadToEnd();
                string ek1 = EncryptHelper.Encrypt(p, key);
                string dk2 = EncryptHelper.Decrypt(ek1, key);
                string ek3 = EncryptHelper.Encrypt(dk2, key);
                using (StreamWriter sw = new StreamWriter(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\" + encryptCertFile))
                {
                    sw.Write(ek3);
                }
            }

            //解密后的文件名
            string decryptCertFile = string.Format("decrypt-cert-{0}.cer", key);
            //3DES解密过程为：P=Dk1(EK2(Dk3(C)))
            using (StreamReader sr = new StreamReader(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\" + encryptCertFile, Encoding.UTF8))
            {
                string c = sr.ReadToEnd();
                string dk3 = EncryptHelper.Decrypt(c, key);
                string ek2 = EncryptHelper.Encrypt(dk3, key);
                string de1 = EncryptHelper.Decrypt(ek2, key);
                using (StreamWriter sw = new StreamWriter(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\" + decryptCertFile))
                {
                    sw.Write(de1);
                }
            }
        }

        protected void btnDownloadFile_Click(object sender, EventArgs e)
        {
            //只处理解密过程
        }

        void EncryptFile(string encryptFile, string key)
        {
            byte[] encryptResult = null;

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = Convert.FromBase64String(key);
            des.Mode = CipherMode.ECB;

            using (StreamReader sr = new StreamReader(encryptFile, Encoding.UTF8))
            {
                byte[] valBytes = Encoding.UTF8.GetBytes(sr.ReadToEnd());
                ICryptoTransform transform = des.CreateEncryptor();

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                    {
                        cs.Write(valBytes, 0, valBytes.Length);
                        cs.FlushFinalBlock();
                        encryptResult = ms.ToArray();
                    }
                }
            }

            using (StreamWriter sw = new StreamWriter(string.Format(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\encrypt-cert-{0}.crt", key)))
            {
                sw.Write(encryptResult);
            }

        }


        private void WriteFile()
        {
            using (FileStream fs = new FileStream(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\cert.crt", FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write("一串信息！");
                }
            }
        }

        private string ReadFile()
        {
            using (FileStream fs = new FileStream(@"G:\Andy-SOB\SOBFS\SobFS.Web\downloads\cert.crt", FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    return sr.ReadToEnd();
                }
            }
        }


        /// <summary>
        /// 生成密钥
        /// <para>随机6位</para>
        /// </summary>
        /// <returns></returns>
        private string BuildEncryptKey()
        {
            string encryptKey = string.Empty;
            char[] keys = "1234567890qwertyuiopPOIUYTREWQ".ToCharArray();
            Random rnd = new Random();
            for (int i = 0; i <6 ; i++)
            {
                encryptKey += keys[new Random(GetRandomSeed()).Next(keys.Length)];
            }
            return encryptKey;
        }

        /// <summary>
        /// 随机因子
        /// </summary>
        /// <returns></returns>
        private int GetRandomSeed()
        {
            byte[] bytes = new byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
            return BitConverter.ToInt32(bytes, 0);
        }




    }


    public class EncryptHelper
    {

        #region ******************************Public Method******************************
        #region ********************加密********************

        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <returns></returns> 
        public static string Encrypt(string content, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(content);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion ********************加密********************

        #region ********************解密********************


        /// <summary>
        /// 解密数据
        /// </summary>
        /// <returns></returns>
        public static string Decrypt(string content, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = content.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(content.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8));
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                }
                return Encoding.Default.GetString(ms.ToArray());
            }
        }

        #endregion ********************解密********************

        #endregion ******************************Public Method******************************

    }
}